import React, { useEffect, useMemo, useReducer, useRef, useState } from "react";
import { Outlet } from 'react-router-dom'

export default () => {
  const [count, setCount] = useState(() => {
    return 1;
  });
  const [age, setAge] = useState(10);

  const addCount = () => setCount(count + 1);
  const addCount1 = () => setCount((state) => state + 1);
  const addAge = () => setAge(age + 1);

  // 在函数组件主体内（这里指在 React 渲染阶段）改变 DOM、添加订阅、设置定时器、记录日志以及执行其他包含副作用的操作都是不被允许的

  useEffect(
    () => {
      // effect 将在每轮渲染结束后执行
      // let num = 1;
      // const timer = setInterval(() => {
      //   console.log(++num);
      // }, 1000);

      // document.addEventListener("click", click);

      // function click() {
      //   console.log("文档被点击了！！");
      // }

      return () => {
        console.log("销毁了！！！！！！！！");
        // clearInterval(timer);
        // document.removeEventListener("click", click);
      };
    },
    [] /*指定依赖的值*/
  );

  //
  const reducer = (state: any, action: any) => {
    switch (action.type) {
      case "ageAdd":
        return { ...state, age: state.age + 1 };
      case "ageSub":
        return { ...state, age: state.age - 1 };
      default:
        return state;
    }
  };
  const [state, dispatch] = useReducer(reducer, { count: 1, age: 20 });

  const [car, setCar] = useState([
    {
      price: 10,
      count: 2,
    },
    {
      price: 100,
      count: 2,
    },
  ]);

  const total = useMemo(() => {
    // console.log("总价计算！！！！");
    return car.reduce((p, n) => {
      return p + n.count * n.price;
    }, 0);
  }, [car]);

  /**********************************************/
  const h1 = useRef<null | HTMLHeadingElement>(null);
  useEffect(() => {
    // document
    // console.log(h1.current)
    if (h1.current) h1.current.style.background = "red";
  }, []);

  return (
    <div>
      <h1 ref={h1}>函数组件</h1>
      <h2>{count}</h2>
      <button onClick={addCount}>+1</button>
      <button onClick={addCount1}>+1</button>
      <h2>{age}</h2>
      <button onClick={addAge}>+1</button>

      <hr />
      <h1>
        {state.count}----{state.age}
      </h1>
      <button onClick={() => dispatch({ type: "ageAdd" })}>age++</button>
      <button onClick={() => dispatch({ type: "ageSub" })}>age--</button>

      <hr />
      <h2>{total}</h2>
      <button
        onClick={() =>
          setCar((state) => {
            const arr = [...state];
            arr[1].count = 10;
            return arr;
          })
        }
      >
        修改
      </button>
      <Outlet></Outlet>
    </div>
  );
};
